var utils = require("../BleMash-js/util.js")
var Ajax = require("../../utils/ajax.js")
var Modal = require("../../utils/modal.js")
var System = require("../../utils/system.js")
var Remote = require("../../utils/remote.js")
var ProxyGenerator = require("../../utils/proxyGenerator.js");
var app = getApp()
Page({
  data: {
    currentpage:0,
    saveinput:'',
    phoneheight: app.globalData.phoneheight,
    warm: 0,
    cold: 0,
    groups:[],
    cons:[],
    lights:[],//c_id,m_id,name,address,devicekey,uuid
    colorData: {
      //基础色相，即左侧色盘右上顶点的颜色，由右侧的色相条控制
      hueData: {
        colorStopRed: 255,
        colorStopGreen: 0,
        colorStopBlue: 0,
      },
      //选择点的信息（左侧色盘上的小圆点，即你选择的颜色）
      pickerData: {
        x: 0, //选择点x轴偏移量
        y: 480, //选择点y轴偏移量
        red: 0,
        green: 0,
        blue: 0,
        hex: '#000000'
      },
      //色相控制条的位置
      barY: 0
    },
    rpxRatio: 0.1, //此值为你的屏幕CSS像素宽度/750，单位rpx实际像素
  },
  onChangeColor(e) {
    this.setData({colorData: e.detail.colorData});
    this.all_control();
  },
  warmchange(e) {
    this.setData({ warm: e.detail.value })
    this.all_control();
  },
  coldchange(e) {
    this.setData({ cold: e.detail.value });
    this.all_control();
  },
  bindchange: function (e) {
    this.setData({currentpage: e.detail.current});
  },
  checkcurrent: function (e) {
    if (this.data.currentpage != e.target.dataset.current) {
      this.setData({currentpage: e.target.dataset.current})
    }
  },
  bindfocus: function (e) {
    var index = e.currentTarget.dataset.index;
    var temp_str;
    switch(this.data.currentpage){
      case 0:
        break;
      case 1:
        temp_str = "lights[" + index + "].changename"
        break;
      case 2:
        temp_str = "groups[" + index + "].changename"
        break;
      case 3:
        temp_str = "cons[" + index + "].changename"
        break;
    }
    this.setData({
      [temp_str]: true
    })

  },
  bindblur: function (e) {
    var index = e.currentTarget.dataset.index;
    var temp_changename;
    var temp_name;
    switch (this.data.currentpage) {
      case 0:
        break;
      case 1:
        temp_changename = "lights[" + index + "].changename";
        temp_name = "lights[" + index + "].name";
        this.setData({
          [temp_changename]: false,
          [temp_name]: this.data.lights[index].name
        })
        break;
      case 2:
        temp_changename = "groups[" + index + "].changename";
        temp_name = "groups[" + index + "].name";
        this.setData({
          [temp_changename]: false,
          [temp_name]: this.data.groups[index].name
        })
        break;
      case 3:
        temp_changename = "cons[" + index + "].changename";
        temp_name = "cons[" + index + "].name";
        this.setData({
          [temp_changename]: false,
          [temp_name]: this.data.cons[index].name
        })
        break;
    }
  },
  saveinput: function (e) {
    this.setData({saveinput: e.detail.value})
  },
  changename: function (e) {
    var index = e.currentTarget.dataset.index;
    switch (this.data.currentpage) {
      case 0:
        break;
      case 1:
        this.changelightname(this.data.lights[index].id, this.data.saveinput, index);
        break;
      case 2:
        this.changegroupname(this.data.groups[index].id, this.data.saveinput, index);
        break;
      case 3:
        this.changecontrollername(this.data.cons[index].c_id,this.data.saveinput, index);
        break;
    }
  },
  changelightname(lightid,newname,index){
    Ajax.AsyncPost("/light/rename_light/", {lightid: lightid,name: newname},(data)=>{
      var temp_str = "lights[" + index + "].name";
      this.setData({ [temp_str]: newname });
    })
  },
  changegroupname(groupid, newname, index){
    Ajax.AsyncPost("/group/rename_group/", { groupid: groupid, name: newname }, (data) => {
      var temp_str = "groups[" + index + "].name";
      this.setData({ [temp_str]: newname});
    })
  },
  changecontrollername(c_id, newname, index){
    Ajax.AsyncPost("/con/rename_con/", { c_id: c_id, name: newname }, (data) => {
      var temp_str = "cons[" + index + "].name";
      this.setData({ [temp_str]: newname });
    })
  },
  all_control: function(){
    var len = this.data.lights.length;
    if (len == 0) return;
    var mesh = app.globalData.activemesh;
    var warm = utils.intToHex(this.data.warm);
    var cold = utils.intToHex(this.data.cold);
    var red = utils.intToHex(this.data.colorData.pickerData.red);
    var green = utils.intToHex(this.data.colorData.pickerData.green);
    var blue = utils.intToHex(this.data.colorData.pickerData.blue);
    mesh.allControl(cold, warm, red, green, blue, (result) => {
      let data = {
        meshid: mesh.id,
        warm: this.data.warm,
        cold: this.data.cold,
        red: this.data.colorData.pickerData.red,
        green: this.data.colorData.pickerData.green,
        blue: this.data.colorData.pickerData.blue
      };
      Ajax.AsyncPost("/mesh/all_control/", data,(res)=>{
        var lights = this.data.lights;
        for (let i=0;i<lights.length;i++){
          lights[i].warm = this.data.warm;
          lights[i].cold = this.data.cold;
          lights[i].red = this.data.colorData.pickerData.red;
          lights[i].green = this.data.colorData.pickerData.green;
          lights[i].blue = this.data.colorData.pickerData.blue;
        }
        this.setData({
          lights:lights
        })
      })
    });
  },
  all_off: function () {
    var len = this.data.lights.length;
    if (len == 0) return;
    var mesh = app.globalData.activemesh;
    mesh.allCloseLight((result) => {
      Ajax.AsyncPost("/mesh/all_off/", { meshid: mesh.id })
    });
  },
  remote_control:function(){
    var red = utils.intToHex(this.data.colorData.pickerData.red);
    var green = utils.intToHex(this.data.colorData.pickerData.green);
    var blue = utils.intToHex(this.data.colorData.pickerData.blue);
    var data={
      addr:'0xFFFF',
      rgb: red+green+blue
    }
    console.log("rgb",data);
    Remote.control(data,(res)=>{
      console.log("get...")
      Remote.gettest();
    });
  },
  remote_off:function(){
    var data = {
      addr: '0xFFFF',
      rgb: '000000'
    }
    console.log("rgb", data);
    Remote.control(data);
  },
  lightcontrol:function(e){
    var index = e.currentTarget.dataset.index;
    var state = this.data.lights[index].state;
    var mesh = app.globalData.activemesh;
    var lights = this.data.lights;
    if (state) {
      this.offlight(lights[index], index);
    } else {
      this.openlight(lights[index], index);
    }
  },
  openlight(light,index){
    var self=this; 88
    var mesh = app.globalData.activemesh;
    var cold = utils.intToHex(light.cold);
    var warm = utils.intToHex(light.warm);
    var red = utils.intToHex(light.red);
    var green = utils.intToHex(light.green);
    var blue = utils.intToHex(light.blue);
    mesh.addressControl(light.deviceaddress, cold, warm, red, green, blue, (value)=> {
      if (value.code == 0) {//开灯成功
        Ajax.AsyncPost("/light/open_light/", {lightid: light.id},(data)=>{})
        var temp_str = "lights[" + index + "].state"
        self.setData({ [temp_str]: 1 })
      } else {//开灯失败
        Modal.showErr(value.message);
      }
    });
  },
  offlight(light,index){
    var self=this;
    var mesh = app.globalData.activemesh;
    mesh.closeLight(light.deviceaddress, function (value) {
      if (value.code == 0) {//关灯成功
        Ajax.AsyncPost("/light/off_light/", { lightid: light.id }, (data) => {})
        var temp_str = "lights[" + index + "].state"
        self.setData({[temp_str]: 0})
      } else {//关灯失败
        Modal.showErr(value.message);
      }
    });
  },
  activategroup: function(e) {
    var index = e.currentTarget.dataset.index;
    app.globalData.activegroup = this.data.groups[index];
  },
  activatecon: function (e) {
    var index = e.currentTarget.dataset.index;
    app.globalData.activecon = this.data.cons[index];
  },
  addgroup:function(e){
    var groupname = "新增组";
    var data = {
      meshid: app.globalData.activemesh.id,
      name: groupname
    };
    Ajax.AsyncPost("/group/add_group/", data, (result) => { 
      this.data.groups.push(result.group);
      this.setData({ groups: this.data.groups});
    })
  },
  deletegroup: function(e){
    var index = e.currentTarget.dataset.index;
    var name = this.data.groups[index].name;
    Modal.showModal("确认要删除组：" + name + "吗？",()=>{
      Ajax.AsyncPost("/group/delete_group/", {groupid: this.data.groups[index].id}, (result) => {
        this.data.groups.splice(e.currentTarget.dataset.index, 1);
        this.setData({ groups: this.data.groups});
      })
    })
  },
  deletelight: function(e){
    var self=this;
    var index = e.currentTarget.dataset.index;
    var name = self.data.lights[index].name;
    var mesh = app.globalData.activemesh;
    Modal.showModal("确认要删除" + name + "吗？", () => {
      Modal.load("删除中");
      var dst = self.data.lights[index].deviceaddress;
      var deviceKey = self.data.lights[index].devicekey;
      var uuid=self.data.lights[index].uuid;
      mesh.removeNode(dst, deviceKey, uuid, (value)=>{
        if (value.code == 0 || value.code == 'ff') {
          Modal.showSuc("删除成功！");
          Ajax.AsyncPost("/light/delete_light_of_mesh/", {
            lightid: self.data.lights[index].id,
            meshid: mesh.id,
          },()=>{
            self.data.lights.splice(index, 1);
            self.setData({
              lights: self.data.lights
            })
            if (mesh.proxyuuid == uuid) self.proxyGenerator.findProxy(app.globalData.activemesh);
          });
        }
      })
    })
  },
  deletecontroller: function(e){
    var self = this;
    var index = e.currentTarget.dataset.index;
    var con = self.data.cons[index];
    var mesh = app.globalData.activemesh;
    Modal.showModal("确认要删除" + con.name + "吗？", () => {
      Modal.load("删除中");
      var dst = con.device_address;
      var deviceKey = con.devicekey;
      var uuid = con.uuid;
      mesh.removeNode(dst, deviceKey, uuid, (value) => {
        if (value.code == 0 || value.code == 'ff') {
          Modal.showSuc("删除成功！");
          Ajax.AsyncPost("/con/delete_con_of_mesh/", {c_id: con.c_id}, () => {
            self.data.cons.splice(index, 1);
            self.setData({cons: self.data.cons})
            if (mesh.proxyuuid == uuid) self.proxyGenerator.findProxy(app.globalData.activemesh);
          });
        }
      })
    })
  },
  onLoad() {
    this.setData({
      phoneheight: app.globalData.phoneheight,
      fix_position: app.globalData.fix_position,
      phonewidth: app.globalData.phonewidth,
      rpxRatio: app.globalData.phonewidth / 750
    });
    this.proxyGenerator = new ProxyGenerator();
    this.proxyGenerator.findProxy(app.globalData.activemesh);
  },
  onShow() {
    var activemesh = app.globalData.activemesh;
    Ajax.AsyncPost("/group/group_list/", { meshid: activemesh.id }, (data) => {
      this.setData({ groups: data.groups });
    })
    Ajax.AsyncPost("/light/light_list/", { meshid: activemesh.id, type: System.getSystem()}, (data) => {
      this.setData({ lights: data.lights });
    })
    Ajax.AsyncPost("/con/con_list/", { meshid: activemesh.id, type: System.getSystem() }, (data) => {
      this.setData({ cons: data.cons });
    })
  },
  onUnload: function (e) {
    app.globalData.activemesh.provisioning_cancle = true;  //跳出页面，本页面的添加动作取消
    app.globalData.activemesh.status = null;  //跳出页面，可以连接代理
    app.globalData.activemesh.stopScan();
  },
})
